package initalize

import (
	"RoccBlog/config"
	"fmt"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
)

// InitGorm 初始化GORM
func InitGorm(conf config.Database) *gorm.DB {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", conf.Username, conf.Password, conf.Host, conf.Port, conf.Db)
	dialector := mysql.Open(dsn)

	db, err := gorm.Open(dialector, &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: logger.Default.LogMode(logger.Info),
	})

	if err != nil {
		log.Fatalln("链接数据库失败！", err.Error())
	}

	return db
}

// RegisterDatabaseTable 注册表
func RegisterDatabaseTable(db *gorm.DB, args ...any) {
	// 添加权限验证实体
	args = append(args, &gormadapter.CasbinRule{})

	// 注册
	if err := db.AutoMigrate(args...); err != nil {
		log.Fatalln("注册表失败！", err.Error())
	}
}
